package com.liam.chinesevietnamesecorpus.config;

import com.liam.chinesevietnamesecorpus.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT拦截器
 * 
 * @author Liam
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestPath = request.getRequestURI();
        
        // 不需要验证的路径
        if (isPublicPath(requestPath)) {
            return true;
        }

        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            log.warn("JWT token缺失，请求路径：{}", requestPath);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"未授权访问\",\"data\":null}");
            return false;
        }

        // 提取token
        String token = authHeader.substring(7);
        
        try {
            // 验证token
            if (jwtUtils.isTokenExpired(token)) {
                log.warn("JWT token已过期，请求路径：{}", requestPath);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":401,\"msg\":\"token已过期\",\"data\":null}");
                return false;
            }

            // 获取用户信息并设置到请求属性中
            String username = jwtUtils.getUsernameFromToken(token);
            Long userId = jwtUtils.getUserIdFromToken(token);
            String role = jwtUtils.getRoleFromToken(token);
            
            request.setAttribute("userId", userId);
            request.setAttribute("username", username);
            request.setAttribute("role", role);
            
            log.debug("JWT验证通过，用户：{}，请求路径：{}", username, requestPath);
            return true;
            
        } catch (Exception e) {
            log.error("JWT验证失败：{}，请求路径：{}", e.getMessage(), requestPath);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"token无效\",\"data\":null}");
            return false;
        }
    }

    /**
     * 判断是否为公开路径（不需要JWT验证）
     */
    private boolean isPublicPath(String path) {
        // 静态资源
        if (path.startsWith("/static/") || path.startsWith("/css/") || path.startsWith("/js/") || path.startsWith("/images/")) {
            return true;
        }
        
        // 登录和注册相关接口
        if (path.startsWith("/user/login") || path.startsWith("/user/register") || path.startsWith("/user/send-verification-code")) {
            return true;
        }
        
        // 根路径和HTML页面
        if (path.equals("/") || path.endsWith(".html") || path.endsWith(".css") || path.endsWith(".js")) {
            return true;
        }
        
        return false;
    }
}
